<style scoped lang="scss">
</style>
<template>
  <div class="app-container">
    <div class="">
      <el-form :inline="true" :model="listQuery">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="">
              <el-input v-model="listQueryFieldValue" placeholder="请输入内容" class="input-with-select" clearable>
                <el-select slot="prepend" v-model="listQueryField" placeholder="请选择" style="width: 120px">
                  <el-option v-for="(item,key) in listQueryFieldMap" :key="key" :value="item.field" :label="item.label">{{ item.label }}</el-option>
                </el-select>
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button v-waves plain class="filter-item" @click="resetGetList()">重置</el-button>
              <el-button v-waves type="primary" icon="el-icon-search" class="filter-item" @click="getList">搜索</el-button>
            </el-form-item>
          </el-col>
          <el-col :span="12" style="display: flex;flex-direction: row-reverse">
            <el-form-item>
              <el-button v-permission="['action:system:user:create']" v-waves type="primary" icon="el-icon-circle-plus-outline" class="filter-item" @click="clickCreate">新增用户</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <el-table
      v-loading="listLoading"
      :data="list"
      fit
      highlight-current-row
      border
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
    >
      <el-table-column align="center" type="index" width="70" label="序号" />
      <el-table-column label="用户名" prop="username" />
      <el-table-column label="姓名" prop="name" />
      <el-table-column label="手机号" prop="phone" />
      <el-table-column label="是否超管" prop="is_super" width="120">
        <template v-slot="scope">
          <el-switch
            v-model="scope.row.is_super"
            class="custom-switch"
            inline-prompt
            disabled
            :active-value="1"
            :inactive-value="0"
          />
        </template>
      </el-table-column>
      <el-table-column label="角色" prop="roles" min-width="150">
        <template v-slot="scope">
          <el-tag
            v-for="item in scope.row.roles"
            :key="item.id"
            type="success"
            style="margin-right: 5px"
          >
            {{ item.name }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="最后登录IP" prop="ip" />
      <el-table-column label="最后登录时间" prop="login_at" />
      <el-table-column label="创建时间" prop="created_at" />
      <el-table-column label="更新时间" prop="updated_at" />
      <el-table-column fixed="right" label="操作" width="300">
        <template v-slot="scope">
          <el-button v-permission="['action:system:user:resetPassword']" v-waves type="primary" size="mini" icon="el-icon-unlock" @click="clickResetPassword(scope.row)">重置密码</el-button>
          <el-button v-permission="['action:system:user:update']" v-waves type="primary" size="mini" icon="el-icon-edit-outline" @click="clickUpdate(scope.row)">编辑</el-button>
          <el-button v-permission="['action:system:user:delete']" v-waves type="danger" size="mini" icon="el-icon-delete" @click="clickDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.page_size" @pagination="getList" />

    <!-- 新增|编辑用户弹窗 -->
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :title="formTitle" :visible.sync="formVisible" width="30%">
      <el-form ref="refForm" :model="form" :rules="rules" label-position="left" label-width="90px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model.trim="form.username" clearable />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="form.name" clearable />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="form.phone" clearable />
        </el-form-item>
        <el-form-item label="角色" prop="role_ids">
          <el-select v-model="form.role_ids" multiple clearable placeholder="请选择" label="角色" style="width: 100%;">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-waves @click="formVisible = false">关闭</el-button>
        <el-button v-if="form.id === 0" v-permission="['action:system:user:create']" v-waves type="primary" @click="submitCreate()">确认新增</el-button>
        <el-button v-else v-permission="['action:system:user:update']" v-waves type="primary" @click="submitUpdate()">确认修改</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Pagination from '@/components/Pagination/index.vue' // Secondary package based on el-pagination
import { userList, createUser, updateUser, deleteUser, resetUserPassword } from '@/api/system/user'
import { roleList } from '@/api/system/role'
export default {
  name: 'SystemUserIndex',
  components: { Pagination },
  data() {
    return {
      list: null,
      total: 0,
      listLoading: false,
      listQueryFieldMap: [
        { field: 'username', label: '用户名' },
        { field: 'phone', label: '手机号' },
        { field: 'keyword', label: '关键字' }
      ],
      listQueryField: 'username',
      listQueryFieldValue: null,
      listQuery: {
        page: 1,
        page_size: 10,
        username: '',
        phone: '',
        keyword: ''
      },
      formTitle: '新增',
      formVisible: false,
      form: {
        id: 0,
        username: '',
        name: '',
        phone: '',
        avatar: '',
        role_ids: []
      },
      rules: {
        username: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        name: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      roleList: []
    }
  },
  watch: {
    listQueryField(newField, oldField) {
      this.listQuery[newField] = this.listQueryFieldValue
      this.listQuery[oldField] = null
    },
    listQueryFieldValue(newValue, oldValue) {
      this.listQuery[this.listQueryField] = newValue
    }
  },
  created() {
    this.getList()
  },
  methods: {
    resetGetList() {
      this.listQuery = {
        page: 1,
        page_size: 10,
        keyword: ''
      }
      this.listQueryFieldValue = null
      this.getList()
    },
    getList() {
      this.listLoading = true
      userList(this.listQuery).then(res => {
        this.list = res.list
        this.total = res.total
      })
      this.listLoading = false
    },
    getRoleList() {
      roleList({ page: 1, page_size: 9999999 }).then(res => {
        this.roleList = res.list
      })
    },
    resetFormData() {
      this.form = {
        id: 0,
        username: '',
        phone: '',
        name: '',
        avatar: '',
        role_ids: []
      }
    },
    clickCreate() {
      this.getRoleList()
      this.resetFormData()
      this.formTitle = '新增'
      this.formVisible = true
    },
    submitCreate() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          createUser(this.form).then(res => {
            this.getList()
            this.$message({
              message: '创建成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {})
        }
      })
    },
    clickUpdate(item) {
      this.form = {
        id: item.id,
        username: item.username,
        phone: item.phone,
        name: item.name,
        avatar: item.avatar,
        role_ids: []
      }
      if (item.roles && item.roles.length > 0) {
        for (const role of item.roles) {
          this.form.role_ids.push(role.id)
        }
      }

      this.getRoleList()
      this.formTitle = '编辑'
      this.formVisible = true
    },
    submitUpdate() {
      this.$refs['refForm'].validate((valid) => {
        if (valid) {
          updateUser(this.form).then(res => {
            this.getList()
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
            this.formVisible = false
          }).then(res => {})
        }
      })
    },
    clickDelete(item) {
      this.$confirm(`此操作将永久删除该用户[${item.username}], 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.submitDelete(item.id)
        this.getList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    submitDelete(id) {
      deleteUser({ id: id }).then(res => {
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.formVisible = false
      }).then(res => {})
    },
    clickResetPassword(item) {
      this.$confirm(`此操作将重置该用户[${item.username}]密码, 是否继续?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.resetUserPassword(item.id)
        this.getList()
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetUserPassword(id) {
      resetUserPassword({ id: id }).then(res => {
        this.getList()
        this.$message({
          message: '删除成功',
          type: 'success'
        })
        this.formVisible = false
      }).then(res => {})
    }
  }
}
</script>
